package com.yan.msmservice.controller;

import com.alibaba.nacos.client.naming.utils.StringUtils;
import com.yan.commonutils.R;
import com.yan.msmservice.service.MsmService;
import com.yan.msmservice.utils.RandomUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @ApiOperation(value = "阿里云发送短信验证码")
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
//        1、从redis中获取验证码的值，如果能获取则直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }

//        如果redis中获取不到，则进行阿里云发送

//        生成随机值传到阿里云进行发送
         code= RandomUtil.getSixBitRandom();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",code);
        boolean isSend=msmService.send(param,phone);
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{

        }
        return R.error().message("短信发送失败！");


    }


}
